package com.gzz.mybatis.common.conditices.section;

import com.gzz.orchid.common.boot.mybatis.conditices.ISection;
import com.gzz.orchid.common.boot.mybatis.conditices.rule.AbstractRegular;
import com.gzz.orchid.common.boot.mybatis.conditices.rule.IRegular;
import com.gzz.orchid.common.boot.mybatis.conditices.rule.SqlSymbol;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;

/**
 * @author higmd
 */
@Slf4j
public abstract class AbstractSection<Children extends AbstractSection<Children>> implements ISection {
    private final Children self =(Children) this;
    protected abstract Children instance();
    // 最后一个规则
    protected SqlSymbol lastSymbol;
    SqlSymbol firstSymbol;
    // 规则列表
    List<ISection> regularList;

    public AbstractSection(){
        regularList = new ArrayList<>();
    }

    private  void add(IRegular regular){
        regularList.add(regular);
        this.lastSymbol = regular.getSymbol();
    }

    @Override
    public String resolveExpression() {
        StringBuilder sb = new StringBuilder();
        for(ISection item : regularList){
            if(item instanceof AbstractRegular regular){
                // log.info("Regular: {}, pre {}",regular.getSymbol(),regular.getPrevious());
                if(regular.getSymbol() == SqlSymbol.OR){
                    sb.append(regular.resolveExpression());
                }else {
                    if (Objects.nonNull(regular.getPrevious()) && regular.getPrevious() != SqlSymbol.OR) {
                        sb.append(" and ");
                    }
                    sb.append(regular.resolveExpression());
                }
            }else if(item instanceof AbstractSection<?> section){
                // log.info("SQL-Section:  last:{},  first: {}", section.lastSymbol, section.firstSymbol);
                sb.append(String.format(" and (%s)", section.resolveExpression()) );
            }

//            if(Objects.nonNull(regular.getSymbol())){
//                sb.append(String.format(" %s ", regular.getSymbol().getSqlSegment()));
//            }
//            sb.append(regular.resolveExpression());
        }
        return sb.toString();
    }

    // 添加规则
    protected Children appendRegular(boolean condition, IRegular regular) {
        if (condition) {
            this.add(regular);
        }
        return self;
    }

    // 添加子查询
    protected Children appendSection(boolean condition,Consumer<Children> consumer, SqlSymbol symbol) {
        if (condition) {
            var isnt = this.instance();
            isnt.lastSymbol = null;
            isnt.firstSymbol = symbol;
            consumer.accept(isnt);
            regularList.add(isnt);
        }
        return self;
    }
}
